package com.flowplan.project.controller;

import com.flowplan.auth.util.JwtTokenUtil;
import com.flowplan.common.dto.ApiResponse;
import com.flowplan.entity.enums.ProjectStatus;
import com.flowplan.project.dto.ProjectCreateRequest;
import com.flowplan.project.dto.ProjectResponse;
import com.flowplan.project.dto.ProjectUpdateRequest;
import com.flowplan.project.service.ProjectService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 项目管理控制器
 * 
 * @author FlowPlan Team
 */
@Slf4j
@RestController
@RequestMapping("/projects")
public class ProjectController {
    
    @Autowired
    private ProjectService projectService;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Value("${jwt.header}")
    private String tokenHeader;
    
    @Value("${jwt.prefix}")
    private String tokenPrefix;
    
    /**
     * 创建项目
     */
    @PostMapping
    @PreAuthorize("hasRole('ADMIN') or hasRole('DEVELOPER') or hasRole('DEMANDER')")
    public ResponseEntity<ApiResponse<ProjectResponse>> createProject(
            @Valid @RequestBody ProjectCreateRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            ProjectResponse response = projectService.createProject(request, userId);
            return ResponseEntity.ok(ApiResponse.success("项目创建成功", response));
        } catch (Exception e) {
            log.error("创建项目失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "创建项目失败: " + e.getMessage()));
        }
    }
    
    /**
     * 更新项目
     */
    @PutMapping("/{projectId}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('DEVELOPER') or hasRole('DEMANDER')")
    public ResponseEntity<ApiResponse<ProjectResponse>> updateProject(
            @PathVariable Long projectId,
            @Valid @RequestBody ProjectUpdateRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            ProjectResponse response = projectService.updateProject(projectId, request, userId);
            return ResponseEntity.ok(ApiResponse.success("项目更新成功", response));
        } catch (Exception e) {
            log.error("更新项目失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "更新项目失败: " + e.getMessage()));
        }
    }
    
    /**
     * 删除项目
     */
    @DeleteMapping("/{projectId}")
    @PreAuthorize("hasRole('ADMIN') or hasRole('DEVELOPER') or hasRole('DEMANDER')")
    public ResponseEntity<ApiResponse<Void>> deleteProject(
            @PathVariable Long projectId,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            projectService.deleteProject(projectId, userId);
            return ResponseEntity.ok(ApiResponse.success("项目删除成功"));
        } catch (Exception e) {
            log.error("删除项目失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "删除项目失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取项目详情
     */
    @GetMapping("/{projectId}")
    public ResponseEntity<ApiResponse<ProjectResponse>> getProject(@PathVariable Long projectId) {
        try {
            ProjectResponse response = projectService.getProject(projectId);
            return ResponseEntity.ok(ApiResponse.success("获取项目详情成功", response));
        } catch (Exception e) {
            log.error("获取项目详情失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "获取项目详情失败: " + e.getMessage()));
        }
    }
    
    /**
     * 分页查询项目列表
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Page<ProjectResponse>>> getProjects(
            @RequestParam(required = false) ProjectStatus status,
            @RequestParam(required = false) Long creatorId,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<ProjectResponse> response = projectService.getProjects(status, creatorId, keyword, page, size);
            return ResponseEntity.ok(ApiResponse.success("查询项目列表成功", response));
        } catch (Exception e) {
            log.error("查询项目列表失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "查询项目列表失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取当前用户的项目列表
     */
    @GetMapping("/my")
    public ResponseEntity<ApiResponse<List<ProjectResponse>>> getMyProjects(HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromToken(httpRequest);
            List<ProjectResponse> response = projectService.getUserProjects(userId);
            return ResponseEntity.ok(ApiResponse.success("获取我的项目成功", response));
        } catch (Exception e) {
            log.error("获取我的项目失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "获取我的项目失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取即将到期的项目
     */
    @GetMapping("/near-deadline")
    public ResponseEntity<ApiResponse<List<ProjectResponse>>> getProjectsNearDeadline() {
        try {
            List<ProjectResponse> response = projectService.getProjectsNearDeadline();
            return ResponseEntity.ok(ApiResponse.success("获取即将到期项目成功", response));
        } catch (Exception e) {
            log.error("获取即将到期项目失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "获取即将到期项目失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取已过期的项目
     */
    @GetMapping("/overdue")
    public ResponseEntity<ApiResponse<List<ProjectResponse>>> getOverdueProjects() {
        try {
            List<ProjectResponse> response = projectService.getOverdueProjects();
            return ResponseEntity.ok(ApiResponse.success("获取已过期项目成功", response));
        } catch (Exception e) {
            log.error("获取已过期项目失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error(400, "获取已过期项目失败: " + e.getMessage()));
        }
    }
    
    /**
     * 从Token中获取用户ID
     */
    private Long getUserIdFromToken(HttpServletRequest request) {
        String bearerToken = request.getHeader(tokenHeader);
        if (bearerToken != null && bearerToken.startsWith(tokenPrefix)) {
            String token = bearerToken.substring(tokenPrefix.length());
            return jwtTokenUtil.getUserIdFromToken(token);
        }
        throw new RuntimeException("无效的Token");
    }
}